import React from 'react'
import { Flex, Toast } from 'antd-mobile'
import SearchHeader from '../../components/SearchHeader'
import HouseItem from '../../components/HouseItem'
import NoHouse from '../../components/NoHouse'
import Filter from './components/Filter'
import Sticky from '../../components/Sticky'
import { getCurrentCity } from '../../utils'
import {
  List,
  AutoSizer,
  WindowScroller,
  InfiniteLoader
} from 'react-virtualized'
import styles from './index.module.scss'
import { getHousesListApi } from '@/api/house'

export default class HouseList extends React.Component {
  // 初始化实例属性
  filters = {}
  state = {
    // 列表数据
    list: [],
    // 总条数
    count: 0,
    // 数据是否加载中
    isLoading: false,
    label: '',
    value: ''
  }

  componentDidMount () {
    // 调用 searchHouseList，来获取房屋列表数据
    this.searchHouseList()
  }
  // 发送请求，获取数据
  async searchHouseList () {
    Toast.loading('加载中...', 0, null, false)
    // 获取当前定位城市id
    this.setState(() => {
      return {
        isLoading: true
      }
    })
    const { label, value } = await getCurrentCity()
    this.setState({
      label,
      value
    })
    let params = {
      cityId: value,
      ...this.filters,
      start: 1,
      end: 20
    }
    const { data: res } = await getHousesListApi(params)
    // console.log('homelist', res)
    const { list, count } = res.body
    // 将获取到的房屋数据，存储到 state 中
    this.setState(() => {
      return {
        list,
        count,
        // 数据加载完成的状态
        isLoading: false
      }
    })

    // 关闭 loading
    Toast.hide()
    // 提示房源数量
    if (count !== 0) {
      Toast.info(`共找到${count}套房源`, 2, null, false)
    }
  }
  // 筛选条件赋值，然后重新搜所
  onFilter = filters => {
    // 这个赋值很精髓
    this.filters = filters
    // console.log(this.filters)
    // console.log('huselist', filters)
    this.searchHouseList()
  }

  renderHouseList = ({
    key, // Unique key within array of rows
    index, // 索引号
    style // 注意：重点属性，一定要给每一个行数据添加该样式！作用：指定每一行的位置
  }) => {
    const item = this.state.list[index]

    // 判断 house 是否存在
    // 如果不存在，就渲染 loading 元素占位
    if (!item) {
      return (
        <div key={key} style={style}>
          <p className={styles.loading} />
        </div>
      )
    }
    // console.log('222', item)
    return (
      <HouseItem
        onClick={() => this.props.history.push(`/detail/${item.houseCode}`)}
        {...item}
        key={key}
        style={style}
      ></HouseItem>
      // <div>123</div>
    )
  }

  isRowLoaded = ({ index }) => {
    const { list } = this.state
    return !!list[index]
  }
  
  loadMoreRows = ({ startIndex, stopIndex }) => {
    // console.log(startIndex)
    // console.log(stopIndex)
    return new Promise(async resolve => {
      Toast.loading('加载中...', 0, null, false)
      let param = {
        cityId: this.state.value,
        ...this.filters,
        start: startIndex,
        end: stopIndex
      }
      const {
        data: { body }
      } = await getHousesListApi(param)
      // console.log('测试结果', body)
      this.setState({
        list: [...this.state.list, ...body.list],
        isLoading: false
      })
      // 关闭 loading
      Toast.hide()
      resolve()
    })
  }
  // 渲染整个房屋列表
  renderList () {
    const { count, isLoading } = this.state
    // 关键点：在数据加载完成后，再进行 count 的判断
    // 解决方式：如果数据加载中，则不展示 NoHouse 组件
    // 但数据加载完成后，再展示 NoHouse 组件
    if (count === 0 && !isLoading) {
      return <NoHouse>没有找到房源，请您换个搜索条件吧~</NoHouse>
    }
    return (
      <div className={styles.houseitems}>
        <InfiniteLoader
          isRowLoaded={this.isRowLoaded}
          loadMoreRows={this.loadMoreRows}
          rowCount={count}
        >
          {({ onRowsRendered, registerChild }) => (
            <WindowScroller>
              {({ height, isScrolling, scrollTop }) => (
                <AutoSizer>
                  {({ width }) => (
                    <List
                      onRowsRendered={onRowsRendered}
                      ref={registerChild}
                      autoHeight
                      isScrolling={isScrolling}
                      scrollTop={scrollTop}
                      scrollToAlignment='start'
                      width={width}
                      height={height}
                      rowCount={count}
                      rowHeight={120}
                      rowRenderer={this.renderHouseList}
                    />
                  )}
                </AutoSizer>
              )}
            </WindowScroller>
          )}
        </InfiniteLoader>
      </div>
    )
  }
  render () {
    return (
      <div>
        <Flex className={styles.header}>
          <i
            className='iconfont icon-back'
            onClick={() => this.props.history.go(-1)}
          />
          <SearchHeader
            cityName={this.state.label}
            className={styles.searchHeader}
          />
        </Flex>
        <Sticky>
          <Filter onFilter={this.onFilter}></Filter>
        </Sticky>
        {this.renderList()}
        {/* <NoHouse>没有找到房源，请您换个搜索条件吧~</NoHouse> */}
      </div>
    )
  }
}
